import api from '@/api'
import { deepCopy, setPage } from '@/utils/util'


const initPage = {
    size: 10,
    number: 0,
    total: 0,
    pages: 0,
    filter: {
        title: null,
        enabled: null
    }
}

// state
const state = {
    data: {
        answers: []
    },

    ui: {
        page: deepCopy(initPage)
    }
}

// getters
const getters = {
    answers: state => state.data.answers,

    answersTotal: state => state.ui.page.total
}

// actions
const actions = {

    getAnswers({ state, commit }, params) {
        api.getAnswers({
            loading: true,
            method: 'post',
            data: params ? params : state.ui.page,
            success: (res) => {
                const { pages, total } = res
                commit('SETANSWERPAGE', { pages, total })

                let answers = res.content
                commit('SETANSWERS', { answers })
            }
        })
    },

    removeAnswer({ dispatch }, params) {
        api.removeAnswer({
            method: 'post',
            data: params,
            success: (res) => {
                dispatch('getAnswers')
            }
        })
    },

    replyAnswer({ dispatch }, params) {
        api.replyAnswer({
            method: 'put',
            data: params,
            success: (res) => {
                dispatch('getAnswers')
            }
        })
    }

}

// mutations
const mutations = {

    SETANSWERS(state, payload) {
        state.data.answers = payload.answers
    },

    SETANSWERPAGE(state, page) {
        page && setPage(state.ui.page, page)
    }
}

export default {
    state,
    getters,
    actions,
    mutations
}